﻿using System;
using System.IO;
using System.Web;
using System.Web.SessionState;
using EmptyWallGallery.Core;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.FrontEnd.Services
{
    /// <summary>
    /// Summary description for Uploads
    /// </summary>
    public class Uploads : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string strMsg;
            var rnd = new RandomStrings();
            var strUser = context.Request["userName"];
            var strUserId = context.Request["userId"];
            var albumId = context.Request["AlbumId"];
            var jpegImageUpload = context.Request.Files["Filedata"];
            var strFileName = rnd.GenerateRandomString(DateTime.Now) + ".jpg";
            var strFileNameOri = Common.Instance.Utf8ToAscii(jpegImageUpload.FileName).ToLower().Replace("-jpg", "");
            var strFolderUpload = Configs.UserFolder + strUser + @"\" + DateTime.Now.Year + @"\" +
                                  Common.Instance.Right("0" + DateTime.Now.Month, 2) + @"\" +
                                  Common.Instance.Right("0" + DateTime.Now.Day, 2) + @"\";
            

            if (!Directory.Exists(strFolderUpload))
            {
                Directory.CreateDirectory(strFolderUpload);
            }
            jpegImageUpload.SaveAs(strFolderUpload + "o__" + strFileName);

            if (ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + strFileName, 1024, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "700x0__" + strFileName, 700, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "640x0__" + strFileName, 640, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "500x0__" + strFileName, 500, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "160x0__" + strFileName, 160, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "135x0__" + strFileName, 135, 0, "") &&
                ImageUtilities.ResizeImage(jpegImageUpload.InputStream, strFolderUpload + "51x0__" + strFileName, 51, 51, ""))
            {
                strMsg = Core.BLL.Images.Instance.Create(strFileNameOri, "", strFileName, Convert.ToInt32(albumId),
                                                         strUserId)
                             ? "OK"
                             : "Fail";
            }
            else
            {
                strMsg = "Fail";
            }
            context.Response.Write(strMsg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}